import re
import json
import os

patterns = [
    re.compile(r"E/Unity"),  # 匹配 E/Unity
    re.compile(r"E Unity\s+:")  # 匹配 E Unity + 任意空格 + :
]


def check_str(s: any) -> bool:
    """
    检查输入是否为非空字符串且仅包含空格字符

    条件：
    1. 输入不能是 None
    2. 必须是字符串类型
    3. 不能是空字符串 ""
    4. 不能全部由空白字符组成（空格、制表符、换行等）

    :param s: 输入值
    :return: 是否满足条件
    """
    if s is None or not isinstance(s, str):
        return False
    return len(s) > 0 and not re.fullmatch(r'\s+', s) is not None


def validate_ip_port(s: str) -> bool:
    """
    校验字符串是否为合法 IPv4地址 + 端口格式

    条件：
    1. IPv4 必须符合 0.0.0.0 - 255.255.255.255
    2. 端口必须为 1-65535
    3. 不允许前导零（如 127.0.0.1:080 → 无效）
    """
    pattern = (r'^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d):([1-9]\d{0,3}|[1-5]\d{'
               r'4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$')
    _result = re.sub(r'\s+', '', s)  # 正则匹配所有空白符
    return re.match(pattern, _result) is not None


def contains_keywords(_text):
    """
    判断是否包含 报错 关键字
    :param _text: 需要匹配的文本
    :return: 如果包含则返回true
    """
    return any(pattern.search(_text) for pattern in patterns)


def get_json_data(path):
    """
    获取指定路径的json数据

    Args:
        path (str): 指定的json文件路径

    Returns:
        json: 返回该文件的json数据
    """
    try:
        if check_json_path(path):
            with open(path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            return data
        else:
            return {}
    except TypeError as e:
        raise f"错误：数据无法序列化为JSON - {e}"
    except (IOError, OSError) as e:
        raise f"错误：写入文件失败 - {e}"
    except Exception as e:
        raise f"未知错误：{e}"


def write_json_data(path, data):
    """将json数据写入指定文件"""
    try:
        if check_json_path(path):
            with open(path, 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
    except TypeError as e:
        raise f"错误：数据无法序列化为JSON - {e}"
    except (IOError, OSError) as e:
        raise f"错误：写入文件失败 - {e}"
    except Exception as e:
        raise f"未知错误：{e}"


def check_json_path(path):
    """检查json文件"""
    if path == "":
        print("路径错误1")
        return False
    if not os.path.isfile(path):
        print("路径错误2")
        return False
    if not path.endswith(".json"):
        print("路径错误3")
        return False
    return True


def load_file(path):
    """读取指定路径文件内容，如果文件无内容，然会空字符串"""
    try:
        with open(path, "r") as f:
            content = f.read()
            if content:
                return content
            else:
                return ""
    except FileNotFoundError:
        raise "文件不存在"
    except Exception as e:
        raise e


if __name__ == '__main__':
    # # 测试用例
    # test_cases = [
    #     (None, False),  # 非字符串 → 失败
    #     ("", False),  # 空字符串 → 失败
    #     ("   ", False),  # 纯空格 → 成功
    #     ("\t\n", False),  # 含制表符/换行 → 成功
    #     (" hello ", True),  # 含有效字符 → 失败
    #     (123, False),  # 数字类型 → 失败
    #     ([" "], False),  # 列表类型 → 失败
    #     ("127.0.0.1:5555", True)
    # ]
    #
    # for input_val, expected in test_cases:
    #     result = check_str(input_val)
    #     print(f"输入：{repr(input_val):<10} 预期：{expected} 实际：{result} → {'通过' if result == expected else '失败'}")
    #
    # print(validate_ip_port(" 127.0.0.1:5555"))  # True
    # print(validate_ip_port("192. 168.1.1:8080"))  # True
    # print(validate_ip_port("10.0.0.1:0a"))  # False
    # print(validate_ip_port("256.1.1.1:80 a"))  # False

    # with open("D:/data/dataTools/test/log.txt", 'r', encoding='utf-8') as f:
    #     text = f.read()
    #     texts = text.split("\n")
    #     for text in texts:
    #         print(contains_keywords(text))
    ...
